<script setup>
import {
  GetListAPI,
  AddDataAPI,
  EditDataAPI,
  GetDeiltsAPI,
  DelDataAPI,
  DispatchAPI,
  ExecuteAPI,
  AuditAPI,
  RevocationAPI,
  DocumentAuditAPI,
  BatchAuditAPI,
  RatchRevocationAPI,
} from "@/api/device/maintenance/workorder.js";
import { GetTeaListAPI, TreeListAPI } from "@/api/common";
const router = useRouter();
const route = useRoute();
import AddFrom from "./addForm.vue";

import { ElMessage, ElMessageBox } from "element-plus";
// vue3方法实例
const { proxy } = getCurrentInstance();
const { maintenance_work_order_status } = proxy.useDict(
  "maintenance_work_order_status"
);

// 新增 || 修改 || 查看实例
const addFromRef = ref(null);
/**
 * 批量表单实例
 */
const ruleFormRef = ref(null);
// const userStore = useUserStore()

// 储存数据
const ruleForm = ref({});

// 各种状态及小数据
const state = reactive({
  row: [], // 选中数据
  ids: "", // 选中id
  delDisabled: true, // 多选
  examineDisabled: false, // 单选
  btnloading: false, //保存加载状态
  total: 0, // 列表总数量
  isShow: false, // 新增弹窗状态
  auditShow: false, // 新增弹窗状态
  examineShow: false, //审核弹窗
  examineBatchShow: false, //批量审核
  title: "新增", // 标题
  loading: false, // 表格加载状态
  rows: [],
});

/**
 * 按钮控制
 */
const delDisabled = ref(true);
// 按钮枚举
const btnList = ref([]);

// 列表数据
const tabelData = ref([]);
/**
 * 班组
 */
const teamSel = ref([]);

/**
 * 安装地点
 */
const treeList = ref([]);
// 查询条件
const SelectList = ref([
  { label: "保养单号", model: "maintenanceNumber", type: "输入框" },
  { label: "设备编号", model: "deviceCode", type: "输入框" },
  { label: "设备名称", model: "deviceName", type: "输入框" },
  {
    label: "状态",
    model: "status",
    type: "下拉单选",
    opt: maintenance_work_order_status,
    treeList,
  },
  {
    label: "所属班组",
    model: "groupCode",
    type: "下拉单选",
    opt: teamSel,
  },
  {
    label: "设备位置",
    model: "installationLocation",
    type: "设备位置",
  },
]);

// 列表枚举
const column = ref([
  { label: "维保单号", prop: "maintenanceNumber", width: "120" },
  { label: "状态", prop: "status", width: "120" },
  { label: "生成方式", prop: "generationModeDict", width: "120" },
  { label: "所属计划", prop: "planName", width: "120" },
  { label: "设备编码", prop: "deviceCode", width: "120" },
  { label: "设备名称", prop: "deviceName", width: "120" },
  { label: "设备类型", prop: "deviceType", width: "120" },
  { label: "维保项目", prop: "projectType", width: "120" },
  { label: "设备位置", prop: "lineName", width: "120" },
  { label: "创建时间", prop: "createTime", width: "120" },
  { label: "维保开始时间", prop: "maintenanceStartTime", width: "120" },
  { label: "维保结束时间", prop: "maintenanceEndTime", width: "120" },
  { label: "审核时间", prop: "auditTime", width: "120" },
  { label: "实际维保工时", prop: "maintenanceWorkHour", width: "120" },
  // { label: '班组', prop: 'groupName', width: '120' },
  { label: "保养人数", prop: "maintenanceNumberPeople", width: "120" },
  { label: "操作", prop: "x" },
]);

// 查询条件 分页
const query = reactive({
  pageNum: 1,
  pageSize: 10,
});
// 表单校验
const rules = reactive({
  auditOpinion: [
    { required: true, message: "请填写审核意见", trigger: "blur" },
  ],
});
// 初始化按钮
const initBtn = () => {
  btnList.value = [
    {
      label: "新增",
      type: "add",
      hasPermi: "maintenance:workorder:add",
    },
    {
      label: "派工",
      type: "自定义",
      hasPermi: "maintenance:workorder:dispatch",
      emit: "dispatch",
      disabled: delDisabled,
    },
    {
      label: "撤销单据",
      type: "自定义",
      hasPermi: "maintenance:workorder:revoke",
      emit: "revoke",
      disabled: delDisabled,
    },

    {
      label: "审核单据",
      type: "自定义",
      hasPermi: "maintenance:workorder:examine",
      emit: "examine",
      disabled: delDisabled,
    },
    {
      label: "提交审核",
      type: "自定义",
      hasPermi: "maintenance:workorder:review",
      emit: "review",
      disabled: delDisabled,
    },
  ];
};
initBtn();

// 条件查询
const selectSubmit = (obj) => {
  Object.keys(obj).forEach((itemKey) => (query[itemKey] = obj[itemKey]));
  query.id = "";
  getList();
};

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = ({ ids, row }) => {
  console.log(row, ids);
  state.rows = row;
  delDisabled.value = row?.length == 0 || !row;
  state.ids = ids;
};
handleSelectionChange([]);
/**
 * 班组下拉
 */
// 获取班组
const getTeamSel = async () => {
  const { data: res } = await GetTeaListAPI();
  teamSel.value = res;
  console.log(teamSel.value, " teamSel.value");
};
getTeamSel();
// 新增弹窗
const addDic = () => {
  state.title = "新增";
  state.isShow = true;
};

// 修改弹窗
const editDic = async (id) => {
  state.title = "修改";
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 查看弹窗
const seeDic = async (id) => {
  state.title = "查看";
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    state.id = id;
    console.log(state.id, "====");

    state.auditShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 派工
const dispatch = async () => {
  proxy.loading("请求中，请稍后");
  try {
    state.isShow = true;
    state.title = "派工";
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 执行保养
const maintenance = async (id) => {
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    // 判断 只有是派工成员才可执行
    // const suerIdFind = res.groupMemberList.find(item => item.id == userStore.userId || item.id == res.groupMonitor)
    // if (!suerIdFind) return proxy.warningMsg('只能是派工成员执行保养！')
    state.isShow = true;
    state.title = "执行保养";
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

//通过title判断执行事件
const isSub = () => {
  if (state.title == "新增") addSub();
  if (state.title == "修改") editSub();
  if (state.title == "派工") dispatchSub();
  if (state.title == "执行保养") maintenanceSub();
};

// 新增提交后台
const addSub = async () => {
  const result = await addFromRef.value.submit();
  if (!result) return;
  // if (result.maintenanceProjects.length < 1) return proxy.warningMsg('至少选择一条保养项目')
  result.maintenanceProjectIdStr = result.maintenanceProjects
    .map((item) => item.id)
    .join(",");
  state.btnloading = true;
  try {
    await AddDataAPI(result);
    getList();
    close();
    proxy.successMsg("新增成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 修改提交后台
const editSub = async () => {
  const result = await addFromRef.value.submit();
  if (!result) return;
  // if (result.maintenanceProjects.length < 1) return proxy.warningMsg('至少选择一条保养项目')
  // result.maintenanceProjectIdStr = result.maintenanceProjects.map(item => item.id).join(',')
  // 字符串人员
  result.maintenancePeopleIdStr = result.maintenanceNumberPeoplea.join(",");
  // 人数
  result.maintenanceNumberPeople = result.maintenanceNumberPeoplea.length;
  state.btnloading = true;
  try {
    await EditDataAPI(result);
    getList();
    close();
    proxy.successMsg("修改成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 派工提交
const dispatchSub = async () => {
  const result = await addFromRef.value.submit();
  if (!result) return;
  // 字符串人员
  result.maintenancePeopleIdStr = result.maintenanceNumberPeoplea.join(",");
  // 人数
  result.maintenanceNumberPeople = result.maintenanceNumberPeoplea.length;
  result.maintenanceWorkOrderProjectList = result.maintenanceProjectList;
  result.idList = state.ids;
  state.btnloading = true;
  try {
    await DispatchAPI(result);
    getList();
    close();
    handleSelectionChange([]);
    proxy.successMsg("派工成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 执行保养
const maintenanceSub = async () => {
  const result = await addFromRef.value.submit();
  if (!result) return;
  result.maintenanceWorkOrderProjectList = result.maintenanceProjectList;
  state.btnloading = true;
  try {
    await ExecuteAPI(result);
    getList();
    close();
    proxy.successMsg("执行保养成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 审核提交
const eamineSub = async (val) => {
  const result = await addFromRef.value.submit();
  if (!result) return;
  state.btnloading = true;
  try {
    await DocumentAuditAPI({
      id: result.id,
      auditResult: val,
      auditOpinion: result.auditOpinion,
    });
    getList();
    state.examineShow = false;
    proxy.successMsg("审核成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 删除
const remove = async (id) => {
  proxy.loading();
  try {
    const isif = await proxy.DelMessageBox();
    if (!isif) return;
    await DelDataAPI(id);
    getList();
    close();
    proxy.successMsg("删除成功！");
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 提交审核
const review = async () => {
  proxy.loading();
  try {
    const isif = await proxy.MessageBox("是否确认提交审核？");
    if (!isif) return;
    await AuditAPI({ idList: state.ids });
    getList();

    proxy.successMsg("提交成功！");
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 撤销审核
const revoke = async (id) => {
  proxy.loading();
  try {
    const isif = await proxy.MessageBox("是否确认撤销审核？");
    if (!isif) return;
    await RevocationAPI(id);
    getList();

    proxy.successMsg("撤销成功！");
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

/**
 *批量撤销
 */
const revokeBacth = async () => {
  proxy.loading();
  try {
    const isif = await proxy.MessageBox("是否确认撤销审核？");
    if (!isif) return;
    await RatchRevocationAPI({ idList: state.ids });
    getList();
    handleSelectionChange([]);

    proxy.successMsg("撤销成功！");
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

/**
 * 批量审核
 * @param {*} ids
 */

const examineBacth = async () => {
  state.title = "审核";
  state.examineBatchShow = true;
};

/**
 * 批量审核提交
 */

const eamineBatchSub = async (val) => {
  const result = await ruleFormRef.value.validate();
  if (!result) return;
  state.btnloading = true;
  try {
    await BatchAuditAPI({
      idList: state.ids,
      auditResult: val,
      auditOpinion: ruleForm.value.auditOpinion,
    });
    delDisabled.value = true;
    getList();

    state.examineBatchShow = false;
    proxy.successMsg("审核成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 审核单据
const examine = async (id) => {
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    state.examineShow = true;
    state.title = "审核";
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 弹窗取消
const close = () => {
  state.isShow = false;
  state.auditShow = false;
  state.examineBatchShow = false;
  ruleForm.value = {};
};

// 获取列表数据
const getList = async () => {
  state.loading = true;
  try {
    const res = await GetListAPI(query);
    state.total = res.total;
    tabelData.value = res.rows;
  } catch (err) {
    console.error(err);
  } finally {
    state.loading = false;
  }
};
// getList()

/**
 * 判断是否从审核待办
 */
onMounted(() => {
  console.log(router, route.query, "router");
  if (route.query.value) {
    query.id = route.query.value;
  }
  getList();
});
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <p-table
        :loading="state.loading"
        keyId="id"
        :column="column"
        :data="tabelData"
        @change="handleSelectionChange"
        :total="state.total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      >
        <template #buttons>
          <!-- 按钮组件 -->
          <p-button
            :list="btnList"
            @add="addDic"
            @dispatch="dispatch"
            @review="review"
            @examine="examineBacth"
            @revoke="revokeBacth"
          />
        </template>
        <template #columnCell="{ column, record }">
          <p-dictTag
            v-if="column.prop == 'status'"
            :options="maintenance_work_order_status"
            :value="record.status"
          />
          <p-operate
            v-if="column.prop == 'x'"
            :list="[
              // {
              //   icon: 'Edit',
              //   emit: 'edit',
              //   text: '修改',
              //   type: 'primary',
              //   disabled: record.status != 5,
              //   hasPermi: 'maintenance:workorder:edit',
              // },
              {
                icon: 'Delete',
                emit: 'remove',
                text: '删除',
                type: 'danger',
                disabled: record.status != 1,

                hasPermi: 'maintenance:workorder:remove',
              },
              {
                icon: 'Search',
                emit: 'look',
                text: '查看',
                type: 'primary',

                hasPermi: 'maintenance:workorder:query',
              },

              {
                icon: '',
                emit: 'revoke',
                text: '撤销审核',
                type: 'primary',
                disabled: record.status != 5,
                hasPermi: 'maintenance:workorder:revoke',
              },
              {
                icon: '',
                emit: 'examine',
                text: '审核单据',
                type: 'primary',
                disabled: record.status != 5,
                hasPermi: 'maintenance:workorder:examine',
              },
            ]"
            @edit="editDic(record.id)"
            @remove="remove(record.id)"
            @look="seeDic(record.id)"
            @dispatch="dispatch(record.id)"
            @maintenance="maintenance(record.id)"
            @review="review(record.id)"
            @revoke="revoke(record.id)"
            @examine="examine(record.id)"
          />
        </template>
      </p-table>
    </el-card>
    <!-- 新增 || 修改 || 查看弹框 -->
    <p-dialog
      :loading="state.btnloading"
      v-model="state.isShow"
      :title="state.title"
      @ok="isSub"
      @close="close"
      width="60%"
    >
      <template #body>
        <AddFrom
          ref="addFromRef"
          :title="state.title"
          :disabled="state.title != '新增'"
          :data="ruleForm"
        />
      </template>
    </p-dialog>

    <!-- 审核弹窗 -->
    <p-dialog
      :loading="state.btnloading"
      isEamine
      v-model="state.examineShow"
      width="60%"
      :title="state.title"
      @ok="eamineSub"
      @close="close"
    >
      <p-auditHistory title="基本信息" :auditDoc="'301'">
        <AddFrom
          ref="addFromRef"
          :title="state.title"
          :disabled="true"
          :data="ruleForm"
        />
      </p-auditHistory>
    </p-dialog>

    <!-- 批量审核弹窗 -->
    <p-dialog
      :loading="state.btnloading"
      isEamine
      v-model="state.examineBatchShow"
      width="20%"
      :title="state.title"
      @ok="eamineBatchSub"
      @close="close"
    >
      <el-form
        inline
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="审核意见">
          <el-input clearable v-model="ruleForm.auditOpinion" type="textarea" />
        </el-form-item>
      </el-form>
      <div style="text-align: center">共计{{ state.rows.length }}审核单据</div>
    </p-dialog>

    <!-- 审核查看 -->
    <p-dialog
      :loading="state.btnloading"
      v-model="state.auditShow"
      :title="state.title"
      @close="close"
      width="60%"
    >
      <template #body>
        <auditHistory title="工单信息" :auditDoc="state.id">
          <template #body>
            <AddFrom
              ref="addFromRef"
              title="查看"
              :disabled="true"
              :data="ruleForm"
            />
          </template>
        </auditHistory>
      </template>
    </p-dialog>
  </div>
</template>

<style lang="scss" scoped>
.box-card {
  margin-top: 20px;
}
</style>
